from PIL import Image
import os
import numpy as np
from sklearn import decomposition
import pandas as pd
from sklearn.feature_extraction import DictVectorizer
import matplotlib.pyplot as pl
import Image

SIZE = (300, 167)
def img_to_matrix(imageName):
	print(imageName)
	img = Image.open(imageName)
	img = img.convert('1')
	# resizes image to the set size
	img = img.resize(SIZE)

	# get data returns contents of image as a sequence object containing pixel values. Using list makes it a list of pixel values
	#img = list(img.getdata())
	
	#img = np.asarray(img)
	#print (img)
	
	# calling map appies the list function to each element in the img list (the pixel values) to geta list of lists
	# these the same?
	#img = map(list, img)
	# print ( type(img) )
	#img = list(a) for a in img
	#t = []
	#for a in img:
	#	t.append(a)

	img = np.array(img)
	return img

def flatten_image(img):
	#shape is a tuple with dimensions of the image
    """ 
    print("img: ")
    print( img.shape)
    print(" end") 
    """
    tup = img.shape
    a = tup[0]
    b = tup[1]
    s = a * b
    image_wide = img.reshape(1, s)
    return image_wide[0]


img_dir = "images/"
images = [img_dir+ f for f in os.listdir(img_dir)]
labels = ["check" if "check" in f.split('/')[-1] else "drivers_license" for f in images]


data = []
for image in images:
    img = img_to_matrix(image)
    img = flatten_image(img)
    data.append(img)
 
 # Abstract only two features
pca = decomposition.RandomizedPCA(n_components=2)

#X = DictVectorizer()
# Get a 2d array of the abstracted arrays
X = np.array(pca.fit_transform(data))

#y = np.where(np.array(labels)=="check", 1, 0)
y = np.where(np.array(labels)=="check", 1, 0)

df = pd.DataFrame({"x": X[:, 0], "y": X[:, 1], "label":np.where(y==1, "Check", "Driver's License")})
colors = ["red", "yellow"]
for label, color in zip(df['label'].unique(), colors):
    mask = df['label']==label
    pl.scatter(df[mask]['x'], df[mask]['y'], c=color, label=label)
pl.legend()
pl.show()


"""
fig = plt.figure()
ax = fig.add_subplot(111)
p = ax.plot(X[:, 0], X[:, 1], 'b')
ax.set_xlabel('x-points')
ax.set_ylabel('y-points')
ax.set_title('Simple XY point plot')
fig.show() """

"""
pl.scatter(X[:,0], X[:,1])
pl.show()
"""
